package com.zhilianbao.leyaogo.ui.activity.me.setting;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.DelayButton;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liu on 2016/11/19.
 */
public class ChangLoginPwdPhoneActivity extends BaseOkHttpActivity {

    @BindView(R.id.tv_cur_phone_num)
    EditText tvCurPhoneNum;
    @BindView(R.id.get_check_num)
    DelayButton getCheckNum;
    @BindView(R.id.et_input_check_num)
    EditText etInputCheckNum;
    @BindView(R.id.et_input_set_pwd_new)
    EditText etInputSetPwdNew;
    @BindView(R.id.tv_chang_login_pwd_commit)
    TextView tvChangLoginPwdCommit;
    @BindView(R.id.chang_pwd_ori)
    TextView changPwdOri;
    private String phoneNum;
    private String mPhone;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_chang_login_pwd_phone;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initToolbar(getString(R.string.change_login_pwd));
        if (Utils.getUserLoginInfo() != null) {
            phoneNum = Utils.getUserLoginInfo().getUserMobile();
            tvCurPhoneNum.setText(phoneNum);
            tvCurPhoneNum.setEnabled(false);
        }
        etInputCheckNum.addTextChangedListener(setPwdTextWatcher);
        etInputSetPwdNew.addTextChangedListener(setPwdTextWatcher);
        tvChangLoginPwdCommit.setEnabled(false);
        mPhone = tvCurPhoneNum.getText().toString().trim();
    }

    @OnClick({R.id.get_check_num, R.id.tv_chang_login_pwd_commit, R.id.chang_pwd_ori})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_check_num:
                verifyMobilePhone();
                break;
            case R.id.tv_chang_login_pwd_commit:
                String checkNum = etInputCheckNum.getText().toString().trim();
                String pwdNew = etInputSetPwdNew.getText().toString().trim();
                if (CheckUtils.isAllPassword(pwdNew)) {
                    AccountApi.resetPassword(this, mPhone, pwdNew, checkNum, new DialogCallback<Object>(this) {
                        @Override
                        public void onSuccess(Object o, Call call, Response response) {
                            XToastUtils.showShortToast("修改登录密码成功,请重新登录");
                            outLogin();
                            Utils.gotoLogin();
                            finish();
                        }
                    });
                } else {
                    XToastUtils.showShortToast(getString(R.string.new_pwd_wrong));
                }

                break;
            case R.id.chang_pwd_ori:
                Utils.startActivity(this, ChangLoginPwdOriActivity.class);
                finish();
                break;
        }
    }

    public void outLogin() {
        Utils.clear();
//        Utils.unregisterPush();
        LeXiuInitService.getInstance().onLegoLogout();
        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_OUT_LOGIN));
    }

    /**
     * 验证手机号
     */
    private void verifyMobilePhone() {
        if (CheckUtils.isEmpty(mPhone)) {
            XToastUtils.showShortToast(getString(R.string.msg_login_input_mobile));
        }else if(mPhone.length() != 11)  {
            XToastUtils.showShortToast("您输入的号码位数不正确，请输入11位数字号码");
        } else {
            if (CheckUtils.isMobilePhone(mPhone)) {
                getCheckNum.setEnabled(false);
                AccountApi.verifyCellPhone(this, 0, mPhone, new JsonCallback<String>(this) {

                    @Override
                    public void onSuccess(String o, Call call, Response response) {
                        if (o.equals(HttpConfig.MSG_CODE_413 + "")) {// 只有注册过的用户才会发送验证码
                            sendVerifyCode(mPhone, getCheckNum);
                        } else if (o.equals(HttpConfig.MSG_CODE_412 + "")) {// 号码未注册
                            XToastUtils.showShortToast(getString(R.string.unregistered_phone));
                            getCheckNum.setEnabled(true);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        getCheckNum.setEnabled(true);
                    }
                });
            } else {
                XToastUtils.showShortToast( getString(R.string.wrong_phone_number));
            }
        }
    }

    /**
     * 发送验证码请求
     */
    private void sendVerifyCode(String mobile, final DelayButton button) {
        AccountApi.sendVerifyCode(this, mobile, new JsonCallback<Object>(this) {

            @Override
            public void onSuccess(Object o, Call call, Response response) {
                XToastUtils.showShortToast(getString(R.string.send_verify_code_suc));
                getCheckNum.startCountDown();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                getCheckNum.setEnabled(true);
            }
        });
    }

    /**
     *
     */
    private TextWatcher setPwdTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            tvChangLoginPwdCommit.setEnabled(etInputCheckNum.getText().length() != 0 && etInputSetPwdNew.getText().length() != 0);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (setPwdTextWatcher != null) {
            etInputSetPwdNew.removeTextChangedListener(setPwdTextWatcher);
            etInputCheckNum.removeTextChangedListener(setPwdTextWatcher);
            setPwdTextWatcher = null;
        }

    }
}
